<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="950" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm"
				 label-width="110px"
				 label-position="left">
			<el-form-item label="APP平台" prop="app_platform">
				<el-input v-model="form.app_platform" placeholder="请输入APP平台，例：android" disabled clearable></el-input>
			</el-form-item>
			<el-form-item label="版本号" prop="target_version">
				<el-input v-model="form.target_version" placeholder="需要更新到的版本，例：1.5.0" clearable></el-input>
			</el-form-item>
			<el-form-item label="升级版本号" prop="min_version">
				<el-input v-model="form.min_version" placeholder="判断是否强制更新的版本号，例：1.0.0" clearable></el-input>
			</el-form-item>
			<el-form-item label="升级包" prop="file">
				<el-upload
					ref="upload"
					class="upload-demo"
					action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
					:limit="1"
					:on-exceed="handleExceed"
					:auto-upload="true"

					:show-file-list="true"
					:http-request="fnUploadRequest"
					:on-success="handleAvatarSuccess"
					:on-error="handFileError"
					:before-upload="beforeAvatarUpload"
				>
					<template #trigger>
						<el-button type="primary">{{ file_status }}</el-button>
					</template>
					<!--				<el-button class="ml-3" type="success" @click="submitUpload">
										upload to server
									</el-button>-->
					<template #tip>
						<div class="el-upload__tip text-red">
							限制1个文件，新文件将覆盖旧文件
						</div>
					</template>
				</el-upload>
			</el-form-item>
			<el-form-item label="APP地址" prop="app_file_url" v-if="form.app_file_url">
				<el-span>{{ form.app_file_url }}</el-span>
			</el-form-item>
			<el-form-item label="升级文案" prop="app_intro">
				<el-input v-model="form.app_intro" :rows="2" type="textarea" placeholder="请填写升级文案"
						  clearable></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" :disabled="isDisabled" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
//首先第一行引入 ali-oss 插件并配置：
const OSS = require('ali-oss');
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增APP版本',
				edit: '编辑APP版本',
				show: '查看APP版本'
			},
			visible: false,
			isSaveing: false,
			isDisabled:false,
			file_status:'选择文件',
			//阿里oss
			ali_token_info:{},
			client:null,
			//表单数据
			form: {
				id: "",
				app_platform: "android",
				target_version: "",
				min_version: "",
				//app_file: "",
				app_intro: "",
				file: null,
				app_file_url: null,
				file_url:null,
			},
			//验证规则
			rules: {
				app_platform: [
					{required: true, message: '请输入APP平台'}
				],
				target_version: [
					{required: true, message: '请输入版本号'}
				],
				min_version: [
					{required: true, message: '请输入升级版本号'}
				],
				app_intro: [
					{required: true, message: '请输入升级文案'}
				],
			},
		}
	},
	created(){
		this.ossToken();
		this.oss();
	},
	mounted() {
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					const formData = new FormData()
					//表单数据
					formData.append('id', this.form.id)
					formData.append('app_platform', this.form.app_platform)
					formData.append('target_version', this.form.target_version)
					formData.append('min_version', this.form.min_version)
					formData.append('app_intro', this.form.app_intro)
					formData.append('app_file', this.form.app_file)

					let config = {
						headers: {'Content_type': 'multipart/form-data'},
						timeout:120000
					}
					this.isSaveing = true;
					console.log('------------', formData, this.form);
					this.$API['sys.app_version'].store.post(formData, config)
						.then((res) => {
							if (res.code == 0) {
								this.$emit('success', this.form, this.mode)
								this.$message.success("操作成功")
							} else {
								this.$alert(res.message, "提示", {type: 'error'})
							}
						})
						.catch((msg) => {
							this.$alert(msg, "提示", {type: 'error'})
						})
						.finally(() => {
							this.isSaveing = false;
						});
				} else {
					return false;
				}
			})
		},
		//表单注入数据
		setData(data) {
			if (data) {
				this.form.id = data.id
				this.form.app_platform = data.app_platform
				this.form.target_version = data.target_version;
				this.form.min_version = data.min_version;
				this.form.app_file = data.app_file;
				this.form.app_file_url = data.app_file_url;
				this.form.app_intro = data.app_intro;
			}
			//可以和上面一样单个注入，也可以像下面一样直接合并进去
			//Object.assign(this.form, data)
		},

		handFileError(){
			this.$alert('上传失败', "提示", {type: 'error'});
			this.file_status = '上传失败';
			//this.isSaveing = false;
		},
		beforeAvatarUpload(file) {
			const file_name = file.name;
			//获取扩展
			const file_ext = file_name.substring(file_name.lastIndexOf(".")+1);//txt
			if (file_ext != 'apk'){
				this.$alert('只支持apk文件上传', "提示", {type: 'error'});
				return false;
			}
			const file_size_res = file.size / 1024 / 1024 < 100;
			if (!file_size_res){
				this.$alert('文件不能超过100M', "提示", {type: 'error'});
				return false;
			}
			return true;
		},

		fnUploadRequest(options) {
			console.log('ccccccccccc',options);
			//开始上传
			this.setIsUpload();
			try {
				let file = options.file; // 拿到 file
				let fileName = file.name.substr(0, file.name.lastIndexOf('.'))
				let file_ext = file.name.substring(file.name.lastIndexOf(".")+1);
				let date = new Date().getTime()
				let fileNames = `${date}_${fileName}` // 拼接文件名，保证唯一，这里使用时间戳+原文件名
				// 上传文件,这里是上传到OSS的 uploads文件夹下
				let prefix = '';
				if (process.env.NODE_ENV === 'production') {
					//线上
					prefix = 'health/prod/';
				}else{
					prefix = 'health/dev/';
				}
				let store_name = 'app/' + fileNames+'.' + file_ext;
				this.client.put(prefix+'app/' + fileNames+'.' + file_ext, file).then(res => {
					console.log('mmmmmm',res);
					if (res.res.statusCode === 200) {
						this.$message.success("上传成功")
						options.onSuccess(res)
						this.form.app_file_url = res.url;
						this.form.app_file = store_name;
						this.setUploadSuccess();
					} else {
						this.$alert('上传失败', "提示", {type: 'error'});
						options.onError("上传失败")
						this.setUploadError();
					}
				})
			} catch (e) {
				this.$alert('上传失败', "提示", {type: 'error'});
				options.onError("上传失败")
				this.setUploadError();
			}
		},
		submitUpload(){
			//console.log(this.$refs);
		},
		success(response){
			/*this.$alert(`success函数钩子，可用于类似OCR返回信息，return false后阻止后续执行，回调参数打开控制台查看`, {
				title: "提示",
				type: "success"
			})*/
			console.log(response);
			return false;
		},
		handleExceed(files,uploadFiles){
			console.log('ppppppppppppp',files,uploadFiles);
		},
		setIsUpload(){
			this.file_status = '上传中';
			this.isSaveing = true;
			this.isDisabled = true;
		},
		setUploadSuccess(){
			this.file_status = '上传成功';
			this.isSaveing = false;
			this.isDisabled = false;
		},
		setUploadError(msg){
			let title = '上传失败';
			if(msg){
				title += ':'+msg;
			}
			this.file_status = title;
			this.isSaveing = false;
			this.isDisabled = false;
		},
		oss(){

			const client= new OSS({
				bucket: 'yolljk-health-shanghai', // 你的 OSS bucket 名称
				region: 'oss-cn-beijing', // bucket 所在地址，我的是 华北2 北京
				cname:true, // 开启自定义域名上传
				endpoint:"https://oss.yolailehealth.com", // 自己的域名
				timeout: 5 * 60 * 1000,


				// yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
				accessKeyId: this.ali_token_info.accessKeyId,
				accessKeySecret: this.ali_token_info.accessKeySecret,
				stsToken: this.ali_token_info.securityToken,
				// HTTPS (secure: true) or HTTP (secure: false) protocol
				secure: false,
				// 刷新临时访问凭证的时间间隔，单位为毫秒。
				 refreshSTSTokenInterval: 15 * 60 * 1000,
				/*refreshSTSToken: this.refreshToken().then(res => {
					if (res.code == 0) {
						console.log('成功刷新oss token');
						this.ali_token_info.accessKeyId = res.data.accessKeyId;
						this.ali_token_info.accessKeySecret = res.data.accessKeySecret;
						this.ali_token_info.securityToken = res.data.securityToken;
					}
				})*/

			});
			this.client = client;
		},
		ossToken(){
			let ali_token_info = JSON.parse(sessionStorage.getItem('ali_token'));
			let is_refresh = 1;
			let token_time = '';
			let time = '';
			if(ali_token_info.securityToken && ali_token_info.expirationTime){
				token_time = ali_token_info.expirationTime;
				time = parseInt(new Date().getTime() / 1000) + '';
				if ((token_time-30) > time){
					is_refresh = 0;
				}
			}
			if(is_refresh){
				this.$API['common'].ossSts.post().then((res) => {
					if (res.code == 0) {
						sessionStorage.setItem('ali_token', JSON.stringify(res.data));
						ali_token_info = JSON.parse(sessionStorage.getItem('ali_token'));
					}
				}).catch((msg) => {
					this.$alert(msg, "提示", {type: 'error'})
				})
			}
			this.ali_token_info = ali_token_info;
		},
		refreshToken(){
			let ali_token_info = null;
			let res = null;
			this.$API['common'].ossSts.post().then((res) => {
				if (res.code == 0) {
					sessionStorage.setItem('ali_token', JSON.stringify(res.data));
					ali_token_info = JSON.parse(sessionStorage.getItem('ali_token'));
					this.ali_token_info = ali_token_info;
				}
			}).catch((msg) => {
				this.$alert(msg, "提示", {type: 'error'})
			})
			return res;
		}
	},
}
</script>

<style>
</style>
